package net.maku.framework.security.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import net.maku.framework.common.cache.RedisCache;
import net.maku.framework.common.cache.RedisKeys;
import net.maku.framework.security.cache.TokenStoreCache;
import net.maku.framework.security.user.UserDetail;
import net.maku.framework.security.utils.TokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collections;

/**
 * 自定义
 * 认证过滤器
 *
 * @author 阿沐 babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@Component
@AllArgsConstructor
public class AuthenticationTokenFilter extends OncePerRequestFilter {
    private final TokenStoreCache tokenStoreCache;
    private final RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 从请求头中获取 Token
        String accessToken = TokenUtils.getAccessToken(request);
        
        // 检查是否是Oppo Ecpm接口的访问
        String requestURI = request.getRequestURI();
        if (requestURI.equals("/oppo/ecpm/add")) {
            // 尝试从请求头中获取专属token
            String ecpmToken = request.getHeader("Ecpm-Token");
            if (StringUtils.isNotBlank(ecpmToken)) {
                // 从Redis中获取正确的专属token
                String storedToken = (String) redisCache.get(RedisKeys.getOppoEcpmTokenKey());
                
                // 验证专属token是否正确
                if (StringUtils.isNotBlank(storedToken) && storedToken.equals(ecpmToken)) {
                    // 创建一个具有特殊权限的临时认证对象
                    SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_ECPM_API");
                    Authentication authentication = new UsernamePasswordAuthenticationToken(
                            "ecpm_api_user", null, Collections.singletonList(authority));
                    
                    // 创建并设置 SecurityContext
                    SecurityContext context = SecurityContextHolder.createEmptyContext();
                    context.setAuthentication(authentication);
                    SecurityContextHolder.setContext(context);
                    
                    // 继续执行过滤器链
                    chain.doFilter(request, response);
                    return;
                }
            }
        }
        
        // 如果 Token 为空，直接放行请求
        if (StringUtils.isBlank(accessToken)) {
            chain.doFilter(request, response);
            return;
        }

        // 根据 Token 获取用户信息
        UserDetail user = tokenStoreCache.getUser(accessToken);
        // 如果用户信息为空，直接放行请求
        if (user == null) {
            chain.doFilter(request, response);
            return;
        }

        // 创建认证对象
        Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());

        // 创建并设置 SecurityContext
        SecurityContext context = SecurityContextHolder.createEmptyContext();
        context.setAuthentication(authentication);
        SecurityContextHolder.setContext(context);

        // 继续执行过滤器链
        chain.doFilter(request, response);
    }
}
